package situ.com.listview;



import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;

public class ListViewActivity extends AppCompatActivity {
    private ListView mListView;

    //需要适配的数据
    private String[] names = {"京东商城", "QQ", "QQ斗地主", "新浪微博", "天猫",
            "UC浏览器", "微信"};
    //图片集合
    private int[] icons = {R.drawable.jd, R.drawable.qq, R.drawable.dz,
            R.drawable.xl, R.drawable.tm, R.drawable.uc, R.drawable.wx};

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_listview);

        mListView = (ListView) findViewById(R.id.listView);
        MyBaseAdapter myBaseAdapter = new MyBaseAdapter();
        // 将Adapter设置到ListView
        mListView.setAdapter(myBaseAdapter);
    }


    // 自定义适配器:绑定数据和界面
    // 在IDEA解决一些简单错误:Alt+Enter
    class MyBaseAdapter extends BaseAdapter {

        // 得到item的总数量
        @Override
        public int getCount() {
            return names.length;
        }

        // 返回指定position位置的条目对象
        @Override
        public Object getItem(int position) {
            return names[position];
        }

        // 返回item的id
        @Override
        public long getItemId(int position) {
            return position;
        }

        // 将数据和布局绑定，每绑定一行就调用一次getView
        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            ViewHolder viewHolder;
            // 这个if-else结构是为了缓存，避免每次都去加载
            if (convertView == null) {
                convertView = LayoutInflater.from(getApplicationContext()).inflate(R.layout.list_item, parent, false);
                viewHolder = new ViewHolder();
                viewHolder.imageView = (ImageView)convertView.findViewById(R.id.imageView);
                viewHolder.textView = (TextView)convertView.findViewById(R.id.textView);
                convertView.setTag(viewHolder);
            } else {
                viewHolder = (ViewHolder) convertView.getTag();
            }
            // 设置每个Item左边的图片
            viewHolder.imageView.setBackgroundResource(icons[position]);
            viewHolder.textView.setText(names[position]);

            return convertView;
        }

        // 描述每一个Item布局
        class ViewHolder{
            ImageView imageView;
            TextView textView;
        }
    }
}
